package com.goockr.keyboraddemo;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    //Activity最外层的Layout视图
    private View view_Bottom;
    View  rootView;
    RelativeLayout.LayoutParams params;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view_Bottom = findViewById(R.id.view_Bottom);
        rootView=findViewById(R.id.root_View);
        params = (RelativeLayout.LayoutParams)view_Bottom.getLayoutParams();

        //完美解决键盘顶起问题
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                rootView.getWindowVisibleDisplayFrame(r);
                int screenHeight = rootView.getRootView().getHeight();
                int heightDifference = screenHeight - (r.bottom - r.top);
                if(heightDifference>150) params.height=dip2px(MainActivity.this,300.0f);
                else params.height=dip2px(MainActivity.this,200.0f);
                view_Bottom.setLayoutParams(params);
                //Log.e("Keyboard Size, Size: " ,String.valueOf(heightDifference));
            }
        });
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
